import { View, Text, Button } from '@tarojs/components'
import { useState } from 'react'
import Taro from '@tarojs/taro'
import { API_BASE_URL } from '../../../config/env'

const NetworkTest = () => {
  const [testResults, setTestResults] = useState([])
  const [testing, setTesting] = useState(false)

  const testUrls = [
    `${API_BASE_URL}`,
    `${API_BASE_URL}/api/health`,
    `${API_BASE_URL}/uploads/pcproductimg/pc_1757685895753_350145138.jpg`
  ]

  const runNetworkTest = async () => {
    setTesting(true)
    setTestResults([])
    
    console.log('🧪 开始网络连通性测试...')
    
    for (const url of testUrls) {
      try {
        console.log(`🌐 测试URL: ${url}`)
        const startTime = Date.now()
        
        const response = await Taro.request({
          url: url,
          method: 'GET',
          timeout: 10000
        })
        
        const endTime = Date.now()
        const responseTime = endTime - startTime
        
        const result = {
          url,
          success: true,
          statusCode: response.statusCode,
          responseTime,
          message: '连接成功'
        }
        
        setTestResults(prev => [...prev, result])
        console.log(`✅ ${url} - 成功 (${responseTime}ms)`)
        
      } catch (error) {
        const result = {
          url,
          success: false,
          error: error.errMsg || error.message,
          message: '连接失败'
        }
        
        setTestResults(prev => [...prev, result])
        console.log(`❌ ${url} - 失败:`, error)
      }
    }
    
    setTesting(false)
    console.log('🏁 网络测试完成')
  }

  const clearResults = () => {
    setTestResults([])
  }

  return (
    <View className='network-test'>
      <View className='test-header'>
        <Text className='test-title'>🌐 网络连通性测试</Text>
        <Text className='test-subtitle'>当前API地址: {API_BASE_URL}</Text>
      </View>
      
      <View className='test-actions'>
        <Button 
          className='test-button primary'
          onClick={runNetworkTest}
          disabled={testing}
        >
          {testing ? '测试中...' : '开始测试'}
        </Button>
        
        {testResults.length > 0 && (
          <Button 
            className='test-button secondary'
            onClick={clearResults}
          >
            清除结果
          </Button>
        )}
      </View>
      
      {testResults.length > 0 && (
        <View className='test-results'>
          <Text className='results-title'>测试结果:</Text>
          {testResults.map((result, index) => (
            <View key={index} className={`test-result ${result.success ? 'success' : 'error'}`}>
              <View className='result-header'>
                <Text className='result-status'>
                  {result.success ? '✅' : '❌'} {result.message}
                </Text>
                {result.success && result.responseTime && (
                  <Text className='result-time'>{result.responseTime}ms</Text>
                )}
              </View>
              <Text className='result-url'>{result.url}</Text>
              {result.success && (
                <Text className='result-status-code'>状态码: {result.statusCode}</Text>
              )}
              {!result.success && (
                <Text className='result-error'>错误: {result.error}</Text>
              )}
            </View>
          ))}
        </View>
      )}
      
      <View className='test-tips'>
        <Text className='tips-title'>💡 测试说明:</Text>
        <Text className='tips-text'>• 如果所有测试都失败，检查网络连接</Text>
        <Text className='tips-text'>• 如果服务连接成功但图片失败，检查图片文件</Text>
        <Text className='tips-text'>• 如果连接超时，检查防火墙设置</Text>
      </View>
    </View>
  )
}

export default NetworkTest
